<template>
    <el-dialog v-model="show" title="添加用户" @close="noShowEdit">
        <el-form :model="form" :rules="rules" ref="formRef">
            <el-form-item label="账号" prop="username" label-width="100px">
                <el-input v-model="form.username" autocomplete="off" />
            </el-form-item>
            <el-form-item label="姓名" prop="nickName" label-width="100px">
                <el-input v-model="form.nickName" autocomplete="off" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email" label-width="100px">
                <el-input v-model="form.email" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码" prop="password" label-width="100px">
                <el-input :disabled="nowId" v-model="form.password" autocomplete="off" type="password" />
            </el-form-item>
            <el-form-item label="备注" prop="note" label-width="100px">
                <el-input v-model="form.note" autocomplete="off" type="textarea" />
            </el-form-item>
            <el-form-item label="是否启用" label-width="100px">
                <el-radio-group v-model="form.status" class="ml-4">
                    <el-radio :label="1" size="large">是</el-radio>
                    <el-radio :label="0" size="large">否</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="noShowEdit">取消</el-button>
                <el-button type="primary" @click="sureFn"> 确定 </el-button>
            </span>
        </template>
    </el-dialog>
</template>
  
<script setup lang="ts">
import { ElMessage, ElMessageBox, FormInstance } from "element-plus";
import { reactive, ref, watch } from "vue";
import { user } from "@/request";

const form = reactive<IRegisterUserParams>({
    username: "",
    nickName: "",
    email: "",
    password: "",
    note: "",
    status: 0,
});

const emit = defineEmits(['hideEdit', 'refresh'])
// 接收显示隐藏的变量
const props = defineProps({
    show: {
        type: Boolean,
        default: false,
    },
    nowId: {
        type: Number,
        default: 0
    }
});


const rules = reactive({
    username: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 6, max: 20, message: '请输入6到20位字符', trigger: 'blur' },
    ],
    nickName: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
    ],
    email: [
        {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur',
        },
        {
            type: 'email',
            message: '请输入正确的邮箱',
            trigger: ['blur', 'change'],
        },
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
    ]
})

// 点击隐藏
const noShowEdit = () => {
    emit('hideEdit')
}

const formRef = ref<FormInstance>()
// 点击确定
const sureFn = () => {
    // console.log(formRef);
    formRef.value?.validate((valid: boolean) => {
        // console.log(valid);
        if (valid) {
            // 调用 ElMessageBox.confirm 方法以打开 confirm 框
            ElMessageBox.confirm("确定要添加该用户吗？", "添加用户", {
                type: "warning",
                // 两个按钮的内容
                confirmButtonText: "确定",
                cancelButtonText: "取消",
            }).then(() => {
                // 添加用户
                if (props.nowId === 0) {
                    // 点击确定的回调
                    // 发请求把用户添加到后端
                    user.registerUserApi(form).then((res) => {
                        if (res.code === 200) {
                            // 添加成功
                            ElMessage.success("添加用户成功");
                            // 关闭添加的弹出
                            emit("hideEdit");
                            // 通知父组件刷新表格
                            emit("refresh");
                            // 在关闭 dialog 后， 记得清空  -- 自己实现
                            formRef.value?.resetFields()
                        } else {
                            // 添加失败
                            ElMessage.success(res.message + ",请重试");
                        }
                    });
                } else {
                    // 编辑信息
                    // 因为进来的时候已经将用户信息赋值给form了,所以可以直接传form
                    user.updateUserInfo(form as IUserModel).then(res => {
                        if (res.code === 200) {
                            ElMessage.success("修改成功")
                            emit('hideEdit')
                            // 通知父组件刷新表格
                            emit("refresh");
                            formRef.value?.resetFields()
                        }
                    })
                }
            })
                .catch(() => { });
        } else {
            return false;
        }
    })
}


// 监听是否有传入id
watch(() => props.nowId, () => {
    // console.log(props.nowId);
    user.getUserInfo(props.nowId).then(res => {
        if (res.code === 200) {
            // console.log(res.data);
            // Object.assign 也是浅拷贝的一种
            // 可以用来复制对象的可枚举属性到目标对象，利用这个特性可以实现对象属性的合并
            //  Object.assign(target, ...sources)
            // 参数： target--->目标对象   source--->源对象   返回值：target，即目标对象
            // form 表单绑定的form
            Object.assign(form, res.data)
        }
    })
})

// const show = ref(true);
</script>
  
<style scoped>

</style>